package com.lbb.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lbb.waimai.entiry.User;
import com.lbb.waimai.entiry.vo.LoginVo;
import com.lbb.waimai.entiry.vo.UserVo;
import com.lbb.waimai.result.R;
import com.lbb.waimai.service.UserService;
import com.lbb.waimai.utils.JwtHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //注册
    @PostMapping("register")
    public R register(@RequestBody User user) {
        if (!StringUtils.isEmpty(user.getName())) {
            if (user.getPwd().length() < 10
                    || user.getIdCard().length() < 18
                    || user.getPhone().length() < 11) {
                throw new RuntimeException("信息不合法");
            }
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("name", user.getName());
            User one = userService.getOne(wrapper);
            if (one != null) {
                throw new RuntimeException("用户已存在");
            }
        }
        userService.save(user);
        return R.ok();
    }

    //登录
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo) {
        String token = "";
        if (loginVo != null) {
            token = userService.login(loginVo);
        }
        return R.ok().data("token", token);
    }

    //获取个人信息
    @GetMapping("info")
    public R getInfo(HttpServletRequest request) {
        Long userId = JwtHelper.getUserId(request);
        Integer id = Integer.valueOf(userId.toString());
        User user = userService.getById(id);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return R.ok().data("data", userVo);
    }

    //修改个人信息
    @PostMapping("update")
    public R update(HttpServletRequest request, @RequestBody UserVo userVo) {
        if (userVo.getPhone().length() != 11){
            throw new RuntimeException("信息不合法");
        }
        Long userId = JwtHelper.getUserId(request);
        Integer id = Integer.valueOf(userId.toString());
        User user = userService.getById(id);
        BeanUtils.copyProperties(userVo, user);
        userService.updateById(user);
        return R.ok();
    }
}
